package com.bobo.rbac.auth.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.jwt.JWT;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @description:
 * @author: BOBO
 * @time: 2022/7/26 19:27
 */
public class JwtUtils {


    /**
     * 产生token
     * @param username
     * @param minute
     * @return
     */
    public static String createToken(String username,Integer minute){
        String jwt = JWT.create()
                .setPayload("username",username)
                .setKey("bobo".getBytes()).setExpiresAt(DateUtil.offsetMinute(new Date(),minute))//.setExpiresAt(DateTime.of(DateUtil.current() + 1000 * 60 * 30))//token30分钟有效
                .sign();
        return jwt;
    }


    /**
     * 获取登录的用户名
     * @return
     */
    public static String getUsername(){
        RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)attributes;
        HttpServletRequest request = servletRequestAttributes.getRequest();
        String token = request.getHeader("token");
        JWT jwt = JWT.of(token);
        String username = String.valueOf(jwt.getPayload("username"));

        return username;
    }
}
